﻿using System.Net.Sockets;
using System.Text;
using UnityEngine;
using Newtonsoft.Json;

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public abstract class Member:MonoBehaviour
{
    public BaseClient BaseClient { get; set; }
    [JsonProperty]
    public string Id { get { return BaseClient.Id; } }
    [JsonProperty]
    public string Name { get { return BaseClient.Name; } }
    public TcpClient Client { get { return BaseClient.TcpClient; } }
    
    /// <summary>
    /// 当前成员所处的房间
    /// </summary>
    public Room Room { get; set; }
    /// <summary>
    /// 向当前成员发送字节数组
    /// </summary>
    /// <param name="data">要发送的字节数组</param>
    public void Send(byte[] data)
    {
        if (Client != null && Client.Connected)
        {
            NetworkStream stream = Client.GetStream();
            if (stream.CanWrite)
                stream.Write(data, 0, data.Length);
        }   
    }
    /// <summary>
    /// 向当前成员发送字符串
    /// </summary>
    /// <param name="msg">要发送的消息</param>
    public void Send(string msg)
    {
        byte[] data = Encoding.UTF8.GetBytes(msg);
        Send(data);
    }
    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
    /// <summary>
    /// 销毁当前成员所处的对象
    /// </summary>
    public void DestroySelf()
    {
        Destroy(gameObject);
    }
}
